package com.brkj.download;

import java.io.File;
import java.util.List;

import com.brkj.util.ConstAnts;
import com.dgl.sdk.util.FileCache;
import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalDb;

import com.brkj.course.CourseDetailActivity;
import com.brkj.model.DS_Course;
import com.brkj.main.R;
import com.brkj.util.ImgShow;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class DownLoadCourseActivity{

	protected ListView course;
	protected TextView noContent;
	protected Context context;
	private View view;
	private BroadcastReceiver br;
	protected TextView titleText;
	
	protected FinalDb course_db;
	protected List<DS_Course> courseSaveList;
	private boolean isEdit = false;
	private CourseDLAdapter courseAdapter;
	
	public DownLoadCourseActivity(View v, Context context) {

		this.context = context;
		this.view = v;
	}
	
    public void setIsEdit(boolean tag){
    	isEdit  = tag;
    	if(courseAdapter != null){
    		courseAdapter.notifyDataSetInvalidated();
    	}
    }
    
    public boolean getIsEdit(){
    	return isEdit;
    }

    public void Start(TextView t1) {
		
		course_db = FinalDb.create(context,ConstAnts.BRKJ_DOWNLOAD_COURSE_DB);
		
		titleText = t1;
		
		course = (ListView) view.findViewById(R.id.course);
		noContent = (TextView) view.findViewById(R.id.noContent);
		FillContent();
		
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction("com.brkj.dowanloadCourseFinish");
		myIntentFilter.addAction("com.brkj.DeleteAllCourseFinish");

		br = new BroadcastReceiver(){

			@Override
			public void onReceive(Context context, Intent intent) {
				FillContent();
			}
		};
		
		context.registerReceiver(br, myIntentFilter);
	}

	public void Stop(){
		context.unregisterReceiver(br);
	}
	
	protected void FillContent(){
		if(courseSaveList != null){
			courseSaveList.clear();
		}
		
		courseSaveList = 
				course_db.findAllByWhere(DS_Course.class," ifFinish="+CourseDLUnit.FINSHED);

		 if ((courseSaveList.size() > 0) ) { 
			 courseAdapter = new CourseDLAdapter(context, courseSaveList);
			 course.setAdapter(courseAdapter);
			 
			 course.setVisibility(View.VISIBLE);
			 noContent.setVisibility(View.GONE);
		}else{
			course.setVisibility(View.GONE);
			noContent.setVisibility(View.VISIBLE);
		}
		 
		setTitleText();
	}
	
	private void setTitleText(){
		 if ((courseSaveList.size() > 0) ) {
			 titleText.setText("已下载 ("+courseSaveList.size()+")");
		 }else{
			 titleText.setText("已下载 (0)");
		 }
		
	}
	public class CourseDLAdapter extends BaseAdapter{
		private ListItemView listItemView;
		protected LayoutInflater listContainer; 
		private Context context;
		private List<DS_Course> courseList;
		private FinalBitmap fb;
		
		public CourseDLAdapter(Context context, List<DS_Course> courseList){
			this.context = context;
			this.courseList = courseList;
			
			listContainer = LayoutInflater.from(context);
			fb = FinalBitmap.create(context);
		}
		
		private  class ListItemView{
			public ImageView CourseImg;
			public TextView Title;
			public TextView Content;
			public TextView Time;
			public TextView StudyCount;
			public Button delete;
			public TextView teacher;
			public TextView course_time;
			public ImageView download;
		};
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return courseList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public void remove(int position) {
			courseList.remove(position);
			notifyDataSetChanged();
			
			if(getCount() == 0){
				course.setVisibility(View.GONE);
				noContent.setVisibility(View.VISIBLE);
			}
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			// 自定义视图
			listItemView = new ListItemView();
			// 获取list_item布局文件的视图
			if (convertView == null) {
				convertView = listContainer.inflate(R.layout.course_downloaded_item, null);
				// 获取控件对象
				listItemView.CourseImg = (ImageView) convertView.findViewById(R.id.CourseImg);
				listItemView.Title = (TextView) convertView
						.findViewById(R.id.Title);
				listItemView.Content = (TextView) convertView
						.findViewById(R.id.Content);
				listItemView.Time = (TextView) convertView
						.findViewById(R.id.Time);
				listItemView.StudyCount = (TextView) convertView
						.findViewById(R.id.StudyCount);
				listItemView.teacher = (TextView) convertView
						.findViewById(R.id.teacher);
				listItemView.course_time = (TextView) convertView
						.findViewById(R.id.course_time);
				
				listItemView.delete = (Button) convertView
						.findViewById(R.id.delete);

                listItemView.download = (ImageView) convertView
						.findViewById(R.id.download);

				// 设置控件集到convertView
				convertView.setTag(listItemView);
			} else {
				listItemView = (ListItemView) convertView.getTag();
			}

            listItemView.download.setVisibility(View.GONE);

//			fb.display(listItemView.CourseImg, courseList.get(position).getCourseImg());
			ImgShow.display(listItemView.CourseImg, courseList.get(position).getCourseImg());
			
//			ImageLoader.getInstance().displayImage(
//					"http://118.192.9.79:7002/KMELearning//WebFiles/cwFiles/52266A266-BBFF-4482-A6A7-02196AB18763k.jpg"
//					, listItemView.CourseImg);
			listItemView.Title.setText(courseList.get(position).getTitle());
			listItemView.Content.setText(courseList.get(position).getContent());
			listItemView.Time.setText("课程时长：" + courseList.get(position).getTime());
			listItemView.StudyCount.setText(
					"学习(" + courseList.get(position).getStudyCount()+ ")");
			listItemView.teacher.setText("讲师姓名：" + courseList.get(position).getTeacher());
			listItemView.course_time.setText(courseList.get(position).getSubmitTime());
			
			if(getIsEdit()){
				listItemView.delete.setVisibility(View.VISIBLE);
			}else{
				listItemView.delete.setVisibility(View.GONE);
			}
			
			listItemView.delete.setTag(R.id.tag_first, courseList.get(position));
			listItemView.delete.setTag(R.id.tag_second, position);
			listItemView.delete.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					deleteCourse((DS_Course)arg0.getTag(R.id.tag_first));
					remove((Integer)arg0.getTag(R.id.tag_second));
					setTitleText();
				}

			});
			
			convertView.setOnClickListener(new MyClickListener(position));
			
			return convertView;

		}

		protected void deleteCourse(DS_Course course) {
			course_db.delete(course);
			
			String url = course.getVideoAdress();
			if((url==null) || (url.equals(""))){
				return;
			}
			
			try {
				FileCache fileCache = new FileCache(context, ConstAnts.DOWNLOAD_COURSE__DIR);
				File file = new File(fileCache.getAbsolutePathByUrl(url));
			    if (file.isFile() && file.exists()) {  
			        file.delete();  
			    }  
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		class MyClickListener implements OnClickListener{
			private int position;
			
			public MyClickListener(int position){
				this.position = position;
			}
			@Override
			public void onClick(View v) {
				
				Intent intent = new Intent(context, CourseDetailActivity.class);

				intent.putExtra("course", courseList.get(position));

				context.startActivity(intent);
			}
			
		}
	}



}
